package rabbitmq.pushorpull;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class PullConsumer {
    public static void main(String[] args) throws Exception {
        // 1、建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST); // 设置IP
        connectionFactory.setPort(Constants.PORT); // 设置开放的端口号，需要提前开放
        connectionFactory.setUsername(Constants.USER_NAME); // 设置RabbitMQ 的账号
        connectionFactory.setPassword(Constants.PASSWORD); // 设置RabbitMQ 的密码
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST); // 设置 虚拟主机
        Connection connection = connectionFactory.newConnection();
        // 2、开启信道，也就是根据 连接创建信道
        Channel channel = connection.createChannel();
        // 3. 声明队列   使用内置的交换机
        //如果队列不存在, 则创建, 如果队列存在, 则不创建
        channel.queueDeclare(Constants.MESSAGE_QUEUE, true, false, false, null);
        // 4. pull 模式获取消息
        GetResponse getResponse = channel.basicGet(Constants.MESSAGE_QUEUE, true);
        System.out.println("拉模式获取消息: "+ new String(getResponse.getBody(),"UTF-8"));
    }
}
